<template>
  <div class="box">
    <div class="login_center">
      <div class="login_mark"></div>
      <div class="login_from">
        <h3>登录</h3>

        <el-form ref="FormRef" label-width="0" :model="loginForm" :rules="userRules">
          <el-form-item width="100%" prop="username"> 
            <el-input prefix-icon="iconfont icon-user" v-model="loginForm.username"></el-input>
          </el-form-item>
          <el-form-item width="100%" prop="password">
            <el-input prefix-icon="iconfont icon-3702mima" type="password" v-model="loginForm.password"></el-input>
          </el-form-item>
          <el-form-item class="btn">
            <el-button type="info" @click="resetFrom">重置</el-button>
            <el-button type="primary" @click="login">登录</el-button>
          </el-form-item> 
        </el-form>

      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'login',
  data(){
    return {
      // 存储用户密码，用户名
      loginForm:{
        username:'',
        password:''
      },
      // 表单验证规则
       userRules: {
          username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
          ],
          password:[
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
          ]
       },
      //  储存用户登录请求响应的信息
      userInfo:{}
    }
  },
  methods:{
    // 重置保单按钮 resetFields()重置表单且不会触发表单验证规则
    resetFrom(){
      this.$refs.FormRef.resetFields()
    },
    // 登录按钮
    login(){
      this.$refs.FormRef.validate(async (valid)=>{
        // 符合规则验证
        if(!valid) return
        // 发起登录请求
        let result = await this.$API.post('login',this.loginForm)
        this.userInfo = result.data
        // 请求成功
        if(this.userInfo.meta.status == 200){
          this.$message.success('登录成功')
          // 将token保存到会话存储中，也就是token只在打开浏览器才存在
          window.sessionStorage.setItem('token',this.userInfo.data.token)
          // 并跳转到home路由
          this.$router.push('/home')
        }else{
          this.$message.error('登录失败')
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.box{
  height: 100%;
  background-image: url('../assets/bgImg.png');
  background-size: 100% 100%;

  .login_center{
    width: 300px;
    height: 200px;
    padding: 20px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);

    .login_mark{
      width: 100%;
      height: 100%;
      margin: auto;
      position: absolute;
      left: 0;
      top: 0;
      background-color: #000;
      border-radius: 10px;
      opacity: 0.1;
    }
    .login_from{
      
      h3{
        margin: 0 0 10px 0;
        color: rgb(103, 102, 102);
        text-align: center;
      }
      .btn{
        display: flex;
        justify-content: flex-end;
      }
    }
  }
}
</style>